/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.spider.comic.service.impl;

import me.zhengjie.exception.SpiderRunningException;
import me.zhengjie.spider.comic.domain.SpiderComic;
import me.zhengjie.spider.common.SpiderAttributeBean;
import me.zhengjie.spider.common.SpiderConstant;
import me.zhengjie.spider.manager.SpiderComicManager;
import me.zhengjie.spider.util.SpiderUtil;
import me.zhengjie.spider.video.domain.SpiderVideo;
import me.zhengjie.spider.web.domain.SpiderWeb;
import me.zhengjie.spider.web.repository.SpiderWebRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.spider.comic.repository.SpiderComicRepository;
import me.zhengjie.spider.comic.service.SpiderComicService;
import me.zhengjie.spider.comic.service.dto.SpiderComicDto;
import me.zhengjie.spider.comic.service.dto.SpiderComicQueryCriteria;
import me.zhengjie.spider.comic.service.mapstruct.SpiderComicMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
 * @author 雨来
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-07-22
 **/
@Service
@RequiredArgsConstructor
public class SpiderComicServiceImpl implements SpiderComicService {

    private final SpiderComicRepository spiderComicRepository;
    private final SpiderComicMapper spiderComicMapper;
    private final SpiderComicManager spiderComicManager;

    @Override
    public PageResult<SpiderComicDto> queryAll(SpiderComicQueryCriteria criteria, Pageable pageable) {
        Page<SpiderComic> page = spiderComicRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(spiderComicMapper::toDto));
    }

    @Override
    public List<SpiderComicDto> queryAll(SpiderComicQueryCriteria criteria) {
        return spiderComicMapper.toDto(spiderComicRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public SpiderComicDto findById(Long comicId) {
        SpiderComic spiderComic = spiderComicRepository.findById(comicId).orElseGet(SpiderComic::new);
        ValidationUtil.isNull(spiderComic.getComicId(), "SpiderComic", "comicId", comicId);
        return spiderComicMapper.toDto(spiderComic);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SpiderComic resources) {
        resources.setDeletedFlag(false);
        spiderComicRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SpiderComic resources) {
        if (StringUtils.isEmpty(resources.getLocalPath())) {
            resources.setLocalPath(String.format(SpiderConstant.FILE_FOLDER_COMIC, SpiderUtil.getFolderNameByNum(resources.getComicId())));
        }
        SpiderComic spiderComic = spiderComicRepository.findById(resources.getComicId()).orElseGet(SpiderComic::new);
        ValidationUtil.isNull(spiderComic.getComicId(), "SpiderComic", "id", resources.getComicId());
        spiderComic.copy(resources);
        spiderComicRepository.save(spiderComic);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long comicId : ids) {
            spiderComicRepository.deleteById(comicId);
        }
    }

    @Override
    public void download(List<SpiderComicDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SpiderComicDto spiderComic : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("所属网站", spiderComic.getWebId());
            map.put("漫画名字", spiderComic.getAlt());
            map.put("作者", spiderComic.getAuthor());
            map.put("封面图", spiderComic.getImg());
            map.put("漫画详情页地址", spiderComic.getHref());
            map.put("漫画分区", spiderComic.getType());
            map.put("漫画标签", spiderComic.getTag());
            map.put("是否删除0否 1是", spiderComic.getDeletedFlag());
            map.put("简介", spiderComic.getRemark());
            map.put("更新时间", spiderComic.getUpdateTime());
            map.put("创建时间", spiderComic.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<String> queryAllByWebId(Long webId) {
        return spiderComicRepository.findHrefByWebId(webId);
    }

    @Override
    public List<SpiderComicDto> findUnSpiderByWebId(Long webId) {
        List<SpiderComic> allByWebIdAndPlayLinkIsNull = spiderComicRepository.findUnSpiderByWebId(webId);
        return spiderComicMapper.toDto(allByWebIdAndPlayLinkIsNull);
    }

    @Override
    public List<SpiderComic> findByWebId(Long webId) {
        return spiderComicRepository.findByWebId(webId);
    }

    @Override
    public void refresh(SpiderComic resources) {
        SpiderAttributeBean spiderAttributeBean = SpiderAttributeBean.builder().thread(1).build();
        try {
            spiderComicManager.spiderComicContentByComic(resources, spiderAttributeBean);
        } catch (Exception e) {
            throw new SpiderRunningException("[spiderComicContentByComic] 爬取视频详细信息失败！");
        }
    }
}